package com.atguigu.spzx.user.service.impl;

import com.atguigu.spzx.model.pojo.user.Region;
import com.atguigu.spzx.model.pojo.user.UserAddress;
import com.atguigu.spzx.user.mapper.RegionMapper;
import com.atguigu.spzx.user.mapper.UserAddressMapper;
import com.atguigu.spzx.user.service.UserAddressService;
import com.atguigu.spzx.utils.DYLAssert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public void saveUserAddress(UserAddress userAddress) {
        // 如果设为了默认，则需要把其他的改为不是默认
        if (userAddress.getIsDefault() == 1) {
            userAddressMapper.update(new UpdateWrapper<UserAddress>().eq("is_default", 1).set("is_default", 0));
        }
        getFullAddress(userAddress);
        userAddressMapper.insert(userAddress);
    }

    @Override
    public void updateUserAddress(UserAddress userAddress) {
        // 如果设为了默认，则需要把其他的改为不是默认
        if (userAddress.getIsDefault() == 1) {
            userAddressMapper.update(new UpdateWrapper<UserAddress>().eq("is_default", 1).set("is_default", 0));
        }
        getFullAddress(userAddress);
        userAddressMapper.updateById(userAddress);
    }

    public void getFullAddress(UserAddress userAddress) {
        // 设置详细地址
        // 获取省 市 县 名
        StringBuilder stringBuilder = new StringBuilder();
        String provinceName = regionMapper.selectOne(new QueryWrapper<Region>().eq("code", userAddress.getProvinceCode())).getName();
        String cityName = regionMapper.selectOne(new QueryWrapper<Region>().eq("code", userAddress.getCityCode())).getName();
        String districtName = regionMapper.selectOne(new QueryWrapper<Region>().eq("code", userAddress.getDistrictCode())).getName();
        stringBuilder.append(provinceName).append(cityName).append(districtName).append(userAddress.getAddress());
        userAddress.setFullAddress(stringBuilder.toString());
    }
}
